<template>
  <view class="content">
    <top-notification ref="topNotificationRef" :safe-height="false" />

    <view class="computer-info abbas">
      <!-- <view class="color-box" :style="bottomBoxStyle"></view> -->
      <view class="scroll-animation-box" :style="topBoxStyle">
        <view class="color-box" :class="backgroundAnimation"></view>
        <view class="wave-box"></view>
        <view class="background-box">
          <!-- 设备信息 -->
          <view class="computer-title">设备【{{ computerInfo.name }}】</view>
          <view class="computer-status">{{ computerInfo.status }}</view>
          <view class="computer-title">{{ computerInfo.port ? computerInfo.ip + ":" + computerInfo.port : computerInfo.ip }}</view>
          <view style="margin-top: 10rpx; display: flex; gap: 5px">
            <url-icon name="qrcode" width="30" height="30" labelGap="2" @click="openQRCode" />
            <url-icon name="fasong" width="30" height="30" labelGap="2" @click="openUpload" />
          </view>
        </view>
      </view>
    </view>
    <!-- 命令按钮 -->
    <view class="computer-control">
      <view class="swipe"></view>
      <view class="quick-instructions">
        <url-icon name="shezhi" width="30" height="30" label="设置" labelGap="2" @click="open" />
        <url-icon name="shuaxin" width="30" height="30" label="重启" labelGap="2" @click="btnClickHandler('Restart')" />
        <view class="shutdown-btn ranker">
          <url-icon name="guanji2" width="40" height="40" @click="btnClickHandler('TurnOff')" />
        </view>
        <url-icon name="jiesuo" width="30" height="30" label="锁定" labelGap="2" @click="btnClickHandler('LockOn')" />
        <url-icon name="diannao" width="30" height="30" label="息屏" labelGap="2" @click="btnClickHandler('ScreenOff')" />
      </view>
      <!-- 编辑与删除模式 -->
      <view class="switch-box">
        <view class="switch-item-box">
          <switch :checked="isEdit" color="#f0ad4e" @change="editSwitch" />
          <span>编辑模式</span>
        </view>
        <view class="switch-item-box">
          <switch :checked="isDeleteCommand" color="#dd524d" @change="deleteCommandSwitch" />
          <span>删除模式</span>
        </view>
        <view class="switch-item-box">
          <switch :checked="isExport" color="#007aff" @change="exportCommandSwitch" />
          <span>导出模式</span>
        </view>
      </view>

      <view class="scroll-view-box">
        <view class="scroll-head">
          <view v-if="isEdit">
            <span class="scroll-head-title">编辑模式</span>
            <span class="scroll-head-tip">点击自定义指令进行编辑</span>
          </view>
          <view v-else-if="isDeleteCommand">
            <span class="scroll-head-title">删除模式</span>
            <span class="scroll-head-tip">选择自定义指令进行删除</span>
          </view>
          <view v-else-if="isExport">
            <span class="scroll-head-title">导出模式</span>
            <span class="scroll-head-tip">点击选择导出的自定义指令</span>
          </view>
          <view v-else>
            <span class="scroll-head-title">命令模式</span>
            <span class="scroll-head-tip">点击自定义指令发送请求</span>
          </view>
          <button v-if="isExport" class="base-button btn" @click="exportCommand">导出</button>
          <button v-else class="func-button btn" @click="importCommand">导入</button>
        </view>

        <scroll-view class="scroll-view" scroll-y="true">
          <view class="btn-group">
            <button @click="clickBtnHandler(custom)" class="btn base-button" :class="btnStyle(custom)" v-for="custom in computerInfo.custom_command" :key="custom.command">{{ custom.name }}</button>
            <!-- 自定义命令按钮 -->
            <button v-if="!isEdit && !isDeleteCommand && !isExport" @click="openAddCommand" class="func-button btn">
              <uni-icons type="plusempty" size="20" color="#2979ff"></uni-icons>
              自定义命令
            </button>
          </view>
        </scroll-view>
      </view>
      <button class="danger-button del-btn" @click="deleteComputer">删除配置</button>
    </view>
    <!-- 编辑设备信息弹窗 -->
    <computer-form ref="computerPopup" :computer-info="computerInfo" />
    <!-- 自定义命令弹窗 -->
    <command-form ref="commandFormRef" :computer-info="computerInfo" />
    <!-- 批量处理命令 -->
    <view class="delete-fab-btn ibiza-sunset" :class="commandList.length && isDeleteCommand ? 'fabBtnAnimation' : 'fabBtnAnimation_reverse'" :key="isDeleteCommand" @click="deleteCommand">
      <uni-icons type="trash-filled" size="35" color="#ffffff" @click="deleteCommand"></uni-icons>
    </view>
    <!-- 二维码弹窗 -->
    <uni-popup ref="QRCodeBox" type="center" border-radius="20px">
      <view class="qrcode-box">
        <view class="tip">扫一扫，导入设备基本信息</view>
        <image class="qrcode-img" v-if="QRCodeImg.length !== 0" :src="QRCodeImg"></image>
        <view class="error-tip"> </view>
        <view class="copy-btn">
          <button class="base-button btn" @click="copyBaseInfo">导出设备基本信息</button>
          <button class="base-button btn" @click="copyAllInfo">导出设备所有信息</button>
          <view class="tip" style="margin-top: 10px">基本信息：设备名、IP、端口号、密钥</view>
          <view class="tip">所有信息：设备基本信息、自定义命令</view>
        </view>
        <uni-icons class="close-btn" type="close" size="50" color="#eee" @click="closeQRCode"></uni-icons>
      </view>
    </uni-popup>
    <!-- 二维码生成 -->
    <QRCode-create ref="QRCodeRef" />
    <!-- 导入导出窗口组件 -->
    <import-export ref="importExportRef" :computer-info="computerInfo" />
    <!-- 上传文件组件 -->
    <!-- #ifdef H5 -->
    <uploadFiles ref="uploadRef" :computer-info="computerInfo"></uploadFiles>
    <!-- #endif -->
  </view>
</template>

<script setup>
import { getComputerInfo, turnOffCommand, restartCommand, lockOnCommand, screenOffCommand, sendCustomCommand, sendCustomScript } from "@/api/control.js";
import { onPageScroll, onLoad } from "@dcloudio/uni-app";
import { ref, reactive, watch, computed } from "vue";
import useComputerStore from "@/store/modules/computer.js";
import { storeToRefs } from "pinia";
import _ from "lodash";
import importExport from "@/pages/detail/components/importExport";
import { useRouterCheck } from "@/composables/index.js";
import { isAuthPass } from "../../utils/authentication";

useRouterCheck();

// #ifdef H5
// 上传文件示例
const uploadRef = ref();
// #endif
// 打开上传窗口
const openUpload = () => {
  if (isAuthPass()) return;
  // #ifdef H5
  uploadRef.value.open();
  // #endif
  // #ifdef APP-PLUS
  uni.navigateTo({ url: `/pages/upload/index?ip=${computerInfo.ip}&port=${computerInfo.port}` });
  // #endif
};

// 二维码显示弹窗
const QRCodeBox = ref();
// 二维码生成组件
const QRCodeRef = ref();
// 二维码连接（base64）
let QRCodeImg = ref("");
// 二维码弹窗打开
const openQRCode = async () => {
  if (isAuthPass()) return;
  // 判断有没有二维码链接，没有就生成
  if (QRCodeImg.value.length === 0) {
    let data = _.cloneDeep(computerInfo);
    delete data.status;
    data.custom_command = [];
    QRCodeImg.value = await QRCodeRef.value.generateQRCode(JSON.stringify(data));
  }
  QRCodeBox.value.open("center");
};

// 二维码弹窗关闭
const closeQRCode = () => {
  QRCodeBox.value.close();
};

// 复制基本信息
const copyBaseInfo = () => {
  if (isAuthPass()) return;
  let data = _.cloneDeep(computerInfo);
  delete data.status;
  data.custom_command = [];
  uni.setClipboardData({
    data: JSON.stringify([data]),
    success: () => {
      uni.showToast({
        title: "已复制至剪切板",
        icon: "success",
      });
    },
  });
};

// 复制所有信息
const copyAllInfo = () => {
  if (isAuthPass()) return;
  let data = _.cloneDeep(computerInfo);
  delete data.status;
  uni.setClipboardData({
    data: JSON.stringify([data]),
    success: () => {
      uni.showToast({
        title: "已复制至剪切板",
        icon: "success",
      });
    },
  });
};

// 记录滚动距离
const scrollY = ref(0);

// 页面滚动监听
onPageScroll((event) => {
  scrollY.value = event.scrollTop;
});

// 页面上滑时背景和文字上移
const topBoxStyle = computed(() => {
  const height = scrollY.value * 0.6;
  return `transform: translateY(-${height}px)`;
});

// 获取本地存储所有设备信息
const computerStore = useComputerStore();
const { computerList } = storeToRefs(computerStore);

// 当前设备信息
let computerInfo = reactive({
  name: "",
  status: "无状态",
  ip: "0.0.0.0",
  port: "0000",
});

// 当前设备在数组中的下标
let computerIndex = ref(0);

// 顶部背景
let backgroundInfo = ref("scaleAnimation");

let backgroundAnimation = computed(() => {
  let background = "scaleAnimation";
  if (isEdit.value) {
    background = "scaleAnimation_reverse sunonthehorizon";
    backgroundInfo.value = background;
  } else if (isDeleteCommand.value) {
    background = "scaleAnimation_reverse ibiza-sunset";
    backgroundInfo.value = background;
  } else {
    background = backgroundInfo.value.replace("scaleAnimation_reverse", "scaleAnimation");
  }
  return background;
});

// 顶部提示横幅实例
const topNotificationRef = ref();

/**
 *
 * 获取当前设备信息
 */
const thisComputerFilter = (computerList, options) => {
  Object.assign(
    computerInfo,
    computerList.filter((item, index) => {
      computerIndex.value = index;
      return item.ip === options.ip && item.port === options.port;
    })[0] || {
      name: "",
      status: "无状态",
      ip: "0.0.0.0",
      port: "0000",
    }
  );
};

// 路由中传入参数
let options_data = reactive({});

onLoad((options) => {
  options_data = options;
  thisComputerFilter(computerList.value, options_data);
  scanComputer();
});

// 监听设备列表的数据变化
watch(
  () => computerList.value,
  (newVal) => {
    thisComputerFilter(newVal, options_data);
  },
  { deep: true }
);

/**
 *
 * 扫描所有设备判断是否在线
 */
const scanComputer = async () => {
  try {
    let res = await getComputerInfo(computerInfo);
    if (res.code === 200) {
      computerInfo.status = "在线";
    } else {
      computerInfo.status = "离线";
    }
  } catch (err) {
    computerInfo.status = "离线";
  }
};

// 获取弹窗表单实例
const computerPopup = ref();

const open = () => {
  computerPopup.value.openAddComputer();
};

// 节流阀
let isLoading = ref(false);

const throttle = async (func) => {
  if (isLoading.value) return;
  isLoading.value = true;
  uni.showLoading({
    title: "请求执行中",
    mask: true,
  });
  // #ifdef APP-PLUS
  uni.vibrateShort();
  // #endif

  await func();
  isLoading.value = false;
  uni.hideLoading();
};

// 发送指令
const btnClickHandler = (type, customCommand) => {
  throttle(async () => {
    let msg = "";
    let res = {};
    if (type === "TurnOff") {
      msg = "关机";
      res = await turnOffCommand(computerInfo);
    } else if (type === "Restart") {
      msg = "重启";
      res = await restartCommand(computerInfo);
    } else if (type === "LockOn") {
      msg = "锁定";
      res = await lockOnCommand(computerInfo);
    } else if (type === "ScreenOff") {
      msg = "息屏";
      res = await screenOffCommand(computerInfo);
    } else {
      msg = customCommand.name;
      if (customCommand.script_type === "cmd") {
        res = await sendCustomCommand(computerInfo, customCommand);
      } else {
        res = await sendCustomScript(computerInfo, customCommand);
      }
    }

    if (res.code === 200) {
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: `已发送【${msg}】指令`,
      });
    } else {
      topNotificationRef.value.sendPopupTip({
        type: "error",
        message: `【${msg}】执行失败`,
      });
    }
  });
};

// 删除设备
const deleteComputer = () => {
  if (isAuthPass()) return;
  // #ifdef APP-PLUS
  uni.vibrateShort();
  // #endif

  let saveData = _.cloneDeep(computerList.value);
  saveData.splice(computerIndex.value, 1);
  computerStore.updateComputerList(saveData);
  uni.navigateTo({
    url: "/pages/index/index",
  });
};

// 命令窗口
const commandFormRef = ref();

// 打开添加命令窗口
const openAddCommand = () => {
  commandFormRef.value.openAddCommand();
};

// 修改命令
const isEdit = ref(false);

// 修改命令切换
const editSwitch = (e) => {
  // #ifdef APP-PLUS
  uni.vibrateLong();
  // #endif
  isEdit.value = e.detail.value;
  if (isEdit.value) {
    if (isDeleteCommand.value) isDeleteCommand.value = !isDeleteCommand.value;
    if (isExport.value) isExport.value = !isExport.value;
  }
};

// 修改命令
const editCommand = (custom_command) => {
  commandFormRef.value.openAddCommand(custom_command);
};

//按钮命令点击事件
const clickBtnHandler = (custom_command) => {
  if (isEdit.value) {
    editCommand(custom_command);
  } else if (isDeleteCommand.value) {
    chooseCommand(custom_command);
  } else if (isExport.value) {
    chooseCommand(custom_command);
  } else {
    btnClickHandler("CustomCommand", custom_command);
  }
};

// 是否批量删除
let isDeleteCommand = ref(false);

// 删除的命令数组
let commandList = ref([]);

// 批量删除切换
const deleteCommandSwitch = (e) => {
  // #ifdef APP-PLUS
  uni.vibrateLong();
  // #endif
  isDeleteCommand.value = e.detail.value;

  if (isDeleteCommand.value) {
    if (isEdit.value) isEdit.value = !isEdit.value;
    if (isExport.value) isExport.value = !isExport.value;
  }
};

watch(
  () => isDeleteCommand.value,
  (newV) => {
    if (!newV) commandList.value = [];
  }
);

// 选择需要批量删除的命令
const chooseCommand = (custom_command) => {
  let index = commandList.value.indexOf(custom_command);
  if (index === -1) {
    commandList.value.push(custom_command);
  } else {
    commandList.value.splice(index, 1);
  }
};

// 批量删除
const deleteCommand = () => {
  if (isAuthPass()) return;
  uni.vibrateLong();
  let saveData = _.cloneDeep(computerList.value);
  let filterCommand = computerInfo.custom_command.filter((item) => {
    if (!commandList.value.includes(item)) {
      return item;
    }
  });
  saveData[computerIndex.value]["custom_command"] = filterCommand;
  computerStore.updateComputerList(saveData);
};

// 导出模式
let isExport = ref(false);

watch(
  () => isExport.value,
  (newV) => {
    if (!newV) commandList.value = [];
  }
);

// 导出模式切换
const exportCommandSwitch = (e) => {
  // #ifdef APP-PLUS
  uni.vibrateLong();
  // #endif
  isExport.value = e.detail.value;
  if (isExport.value) {
    isEdit.value = false;
    isDeleteCommand.value = false;
  }
};

// 导入导出组件实例
const importExportRef = ref();
// 自定义命令导入
const importCommand = () => {
  importExportRef.value.openInputDialog();
};
// 自定义命令导出
const exportCommand = () => {
  importExportRef.value.openAlertDialog(commandList.value);
};

// 不同状态下的按钮
const btnStyle = (custom) => {
  let style = [];
  if (commandList.value.includes(custom)) {
    if (isDeleteCommand.value) style.push("delete-shadow");
    if (isExport.value) style.push("export-shadow");
  }
  if (custom.permission) {
    style.push("warning-button");
  } else {
    style.push("base-button");
  }

  return style.join(" ");
};
</script>

<style lang="scss" scoped>
.base-background-img {
  background-color: #2979ff;
}
.warning-background-img {
  background-color: #ffbe4f;
}
.danger-background-img {
  background-color: #dd524d;
}

.content {
  position: relative;
  .computer-info {
    height: 100vh;
    width: 100vw;
    .scroll-animation-box {
      height: 100%;
      width: 100%;
      position: fixed;
      top: 0;
      left: 0;
      .color-box {
        height: 150vh;
        width: 150vh;
        position: fixed;
        top: -20vh;
        left: 50%;
        border-radius: 50%;
      }
      .wave-box {
        height: 150vh;
        width: 150vw;
        // background-color: #eee;
        box-shadow: inset 0 0 50px 50px rgba(255, 255, 255, 0.8), 0 50px 50px rgba(255, 255, 255, 0.8);
        transform: translate(-50%, -50%);
        position: fixed;
        top: 50vh;
        left: 50%;
        border-radius: 20%;
        animation: wave 1.5s infinite;
      }
      .background-box {
        height: 100%;
        width: 100%;
        background: url("/static/img/bg4.png") no-repeat center center fixed;
        background-size: cover;
        position: fixed;
        top: 0;
        left: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #eee;
      }
      .computer-title {
        max-width: 600rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: center;
      }
      .computer-status {
        font-size: 90rpx;
        font-weight: bold;
      }
    }
  }

  .computer-control {
    position: absolute;
    background-color: #fff;
    // #ifdef H5
    height: calc(100vh - 44px);
    top: calc(100vh - 149px);
    // #endif

    // #ifdef APP-PLUS
    height: 100vh;
    top: calc(100vh - 105px);
    // #endif
    width: 100vw;
    border-radius: 40rpx 40rpx 0 0;
    padding: 8px 15px 10px 15px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    .swipe {
      background-color: #66666677;
      width: 100rpx;
      height: 6px;
      border-radius: 3px;
      margin-bottom: 11px;
    }

    .quick-instructions {
      height: 70px;
      width: 100%;
      padding-top: 10px;
      background-color: #f7f8fb;
      border-radius: 10px;
      box-sizing: border-box;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-around;

      .shutdown-btn {
        position: relative;
        z-index: 10;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 70px;
        width: 70px;
        margin-top: -10px;
        border-radius: 50px;
        box-shadow: 0 0px 30px rgba(51, 0, 252, 0.2), 0 0px 40px rgba(149, 0, 138, 0.2), 0 0px 50px rgba(235, 0, 0, 0.2);
      }
    }
    .switch-box {
      width: 100%;
      height: 70px;
      background-color: #f7f8fb;
      border-radius: 10px;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .switch-item-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        span {
          margin-top: 5px;
          font-size: 9px;
          color: #3f3f3f83;
        }
      }
    }
    .scroll-view-box {
      height: calc(100vh - 310px);
      width: 100%;
      background-color: #f7f8fb;
      border-radius: 10px;
      .scroll-head {
        padding: 10px 10px 0 10px;
        line-height: 20px;
        display: flex;
        justify-content: space-between;
        .btn {
          margin-top: 10rpx;
          height: 25px;
          line-height: 25px;
          width: 40px;
          padding: 0;
          margin: 0;
          font-size: 12px;
        }
        .scroll-head-title {
          font-size: 20px;
          font-weight: bold;
          color: #444;
        }
        .scroll-head-tip {
          margin-left: 20rpx;
          font-size: 12px;
          color: #999aaa;
        }
      }
      .scroll-view {
        box-sizing: border-box;
        padding: 20rpx 0;
        height: calc(100vh - 350px);
        width: 100%;
        .btn-group {
          display: flex;
          flex-wrap: wrap;
          align-content: flex-start;
        }
      }
    }

    .btn {
      width: 45%;
      margin: 0 2.5% 25rpx 2.5%;
    }
    .del-btn {
      height: 40px;
      width: 100%;
      margin-top: 10px;
    }
  }

  .delete-shadow {
    border: 2px solid #dd524d;
    box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(222, 81, 77, 0.5);
    color: #b82e29a2;
  }

  .delete-shadow {
    border: 2px solid #dd524d;
    box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(222, 81, 77, 0.5);
    color: #b82e29a2;
  }

  .export-shadow {
    border: 2px solid #007aff;
    box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(0, 123, 255, 0.5);
    color: #15406e83;
  }

  .delete-fab-btn {
    position: fixed;
    bottom: 10vh;
    right: 40rpx;
    background-color: #dd524d;
    width: 90rpx;
    height: 90rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50rpx;
    box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(202, 174, 174, 0.4);
  }
  .qrcode-box {
    width: 500rpx;
    padding: 30rpx 0;
    background-color: #eee;
    border-radius: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .tip {
      color: #969896;
      font-size: 12px;
    }
    .qrcode-img {
      margin-top: 10rpx;
      width: 400rpx;
      height: 400rpx;
    }

    .btn {
      height: 35px;
      line-height: 35px;
      font-size: 15px;
      border-radius: 17px;
      margin-top: 20rpx;
    }

    .close-btn {
      position: absolute;
      bottom: -70px;
    }
  }
}
</style>
